package com.peach.controller.UserManage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.peach.domain.ResultVO;
import com.peach.domain.UserManage.User;
import com.peach.service.UserManage.RedisApplication;
import com.peach.service.UserManage.UserApplication;
import com.peach.utils.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserApplication userApplication;
    @Autowired
    private RedisApplication redisApplication;
    @RequestMapping("/login")
    @ResponseBody
    public ResultVO userLogin (HttpServletRequest req , HttpServletResponse res){
        HttpSession session = req.getSession();
        String reqJson = null;
        try {
            reqJson = JsonConfig.getRequestPostStr(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(reqJson);

        //base-vue中的userName即用户的账号
        String id = json.getString("userName");
        String passWord = json.getString("passWord");

        //查询是否存在这个用户
        List<User> users = userApplication.login(new User(id,null,passWord));

        ResultVO rvo = new ResultVO();
        if (users.size() > 0){
            System.out.println(users.get(0).getUserName());
            rvo.setSuccess(true);
            //返还前端用的map和实体类
            Map<String,String> userMap = new HashMap<String,String>();
            User userVO = new User();
            userMap.put("id",id);
            userMap.put("userName",users.get(0).getUserName());
            userMap.put("passWord",passWord);
            userVO.setUser(userMap);
            rvo.setData(userVO);
            session.setAttribute("isLogin",true);
            session.setAttribute("currentUser",id);
        }else {
            rvo.setSuccess(false);
            rvo.setMsg("账号或密码错误");
            session.setAttribute("isLogin",false);
        }
        userApplication.deleteCurrentUser();
        return rvo;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public ResultVO logout (HttpServletRequest req , HttpServletResponse res){

        HttpSession session = req.getSession();

        ResultVO rvo = new ResultVO();
        session.setAttribute("isLogin",false);
        rvo.setSuccess(true);
        rvo.setMsg("注销成功");
        return rvo;
    }

    //SC ： security center
    @RequestMapping("/SC/register")
    @ResponseBody
    public ResultVO register (HttpServletRequest req , HttpServletResponse res){
        String reqJson = null;
        try {
            reqJson = JsonConfig.getRequestPostStr(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(reqJson);
        String id = json.getString("userName");
        String passWord = json.getString("passWord");
        String userName = json.getString("nickName");
        User user = new User(id,userName,passWord);
        System.out.println(id);
        System.out.println(passWord);
        System.out.println(userName);
        ResultVO rvo = new ResultVO();
        int affRows = userApplication.register(user);

        //id已存在
        if (affRows == 1){
            rvo.setSuccess(true);
            rvo.setMsg("注册成功");
        }else {
            rvo.setSuccess(false);
            rvo.setMsg("账号已存在");
        }
        return rvo;
    }

    //SC ： security center
    @RequestMapping("/SC/modifyPassword")
    @ResponseBody
    public ResultVO modifyPassword (HttpServletRequest req , HttpServletResponse res){

        String reqJson = null;
        try {
            reqJson = JsonConfig.getRequestPostStr(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(reqJson);
        String id = json.getString("userName");
        String passWord = json.getString("passWord");
        String newPassWord = json.getString("newPassWord");
        Map<String,String> m = new HashMap<>();
        m.put("id",id);
        m.put("passWord",passWord);
        m.put("newPassWord",newPassWord);
        ResultVO rvo = new ResultVO();
        int affRows = userApplication.modifyPassword(m);

        //id已存在
        if (affRows == 1){
            rvo.setSuccess(true);
            rvo.setMsg("修改成功");
        }else {
            rvo.setSuccess(false);
            rvo.setMsg("修改失败，id不存在");
        }
        return rvo;
    }

    @RequestMapping("/download")
    @ResponseBody
    //此接口只做下载配置文件前的拦截，比如用户权限，是否登录 等等，正式下载文件的url 是另一个原生项目的localhost:8020//file/MDMManage.mobileconfig

    public ResultVO download(HttpServletRequest req,HttpServletResponse res) throws IOException {
        String reqJson = null;
        try {
            reqJson = JsonConfig.getRequestPostStr(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(reqJson);

        //base-vue中的userName即用户的账号
        String id = json.getString("userName");
        String password = json.getString("passWord");
        String nickName = json.getString("nickName");
        System.out.println(id);
        System.out.println("当前准备下载安装配置文件的用户为："+id);
        ResultVO rvo = new ResultVO();
        Map<String,String> m = new HashMap<>();
        m.put("currentUser",id);
        m.put("nickName",nickName);
        m.put("preDownloadTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//存入当前时间
        System.out.println(m.toString());
        //下载的时候添加当前预安装配置文件用户id和当前预安装配置文件设备昵称
        int affRow = userApplication.insertCurrentUser(m);
        //SchedulingConfig中:设置计时器 一分钟后清空此数据库表
        //保存错误
        if (affRow == 0){
            rvo.setSuccess(false);
            rvo.setMsg("获取当前用户错误");
        }else{
            rvo.setSuccess(true);
        }
        return rvo;
    }
    //TODO：查询所有跟"我"有关的消息的接口，即切换到"消息"页中要访问的接口。
    //发送指令的时候

    //登录状态拦截接口
    @RequestMapping("/checkIsLogin")
    @ResponseBody
    public ResultVO checkIsLogin(HttpServletRequest req,HttpServletResponse res) throws IOException {
        ResultVO rvo = new ResultVO();
        String reqJson = null;
        try {
            reqJson = JsonConfig.getRequestPostStr(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(reqJson);
        String id = json.getString("userName");
        System.out.println(id);
        String currentId = req.getSession().getAttribute("currentUser").toString();
        boolean isLogin = (boolean) req.getSession().getAttribute("isLogin");
        if (id != null && currentId != null){
            if (id.equals(currentId) && isLogin) {
                rvo.setSuccess(true);
            }else {
                rvo.setSuccess(false);
            }
        }else {
            rvo.setSuccess(false);
        }
        return rvo;
    }

}
